package controllers;

import java.util.List;

import models.User;
import models.ticket.Ticket;
import models.ticket.TicketCategory;
import models.ticket.TicketMessage;
import play.data.DynamicForm;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;

@Security.Authenticated(Secured.class)
public class TicketController extends Controller {

	public static Result ticket()
	{
		User user = User.find.where().eq("username", session().get("uname")).findUnique();
		
		List<Ticket> tickets = Ticket.find.where().eq("user", user).findList();
		
		return ok();
	}
	
	public static Result showTicket(Long id)
	{
		Ticket ticket = Ticket.find.byId(id);
		User user = User.find.where().eq("username", session().get("uname")).findUnique();
		
		if(ticket.user.id != user.id)
		{
			flash("fail", "Sorry, you don't have access. =(");
			return ok();
		}
		
		return ok();
	}
	
	public static Result replyTicket()
	{
		DynamicForm form = Form.form().bindFromRequest();
		
		Long ticketId = Long.valueOf(form.get("ticketId"));
		
		if(Ticket.find.byId(ticketId).resolved == true)
		{
			return ok();
		}
		
		Long userId = Long.valueOf(User.find.where().eq("username", session().get("uname")).findUnique().id);
		String reply = form.get("reply");
		
		User user = User.find.byId(userId);
		Ticket ticket = Ticket.find.byId(ticketId);
		TicketMessage message = TicketMessage.create(user, reply);
		
		ticket.messages.add(message);
		ticket.save();
		
		return ok();
	}
	
	public static Result newTicket()
	{
		DynamicForm form = Form.form().bindFromRequest();
		
		String title = form.get("title");
		String body = form.get("body");
		String cat = form.get("category");
		
		User user = User.find.where().eq("username", session().get("uname")).findUnique();
		TicketCategory category = TicketCategory.find.where().eq("name", cat).findUnique();
		TicketMessage message = TicketMessage.create(user, body);
		Ticket ticket = Ticket.create(title, category, user, message);
		
		ticket.save();
		return ok();
	}
	
	public static Result closeTicket()
	{
		DynamicForm form = Form.form().bindFromRequest();
		
		Long ticketId = Long.valueOf(form.get("ticketId")); 
		
		Ticket ticket = Ticket.find.byId(ticketId);
		ticket.resolved = true;
		
		return ok();
	}
}
